<template>
  <div class="global-enterprise-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader/>

    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu/>

      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('enterprise.search.title') }}</div>

          <!-- 搜索输入区 -->
          <div class="search-box-container">
            <el-input
                v-model="queryParams.companyName"
                :placeholder="t('enterprise.search.placeholder')"
                clearable
                class="search-input"
                @clear="resetCompanySearch"
                @keyup.enter="fetchEnterprises"
                prefix-icon="el-icon-search"
            ></el-input>

            <el-input
                v-model="queryParams.lastName"
                :placeholder="t('enterprise.search.firstName')"
                clearable
                class="search-input"
                @clear="resetCompanySearch"
                @keyup.enter="fetchEnterprises"
                prefix-icon="el-icon-search"
            ></el-input>

            <el-input
                v-model="queryParams.firstName"
                :placeholder="t('enterprise.search.lastName')"
                clearable
                class="search-input"
                @clear="resetCompanySearch"
                @keyup.enter="fetchEnterprises"
                prefix-icon="el-icon-search"
            ></el-input>
          </div>
        </div>

        <!-- 导出按钮区域 -->
        <div class="export-module">
          <div class="matched-count">
            <span>{{ t('enterprise.matched.count', {count: ''}) }}</span>
            <span class="matched-count-number">{{ formattedTotalEnterprise }}</span>
          </div>
          <el-button
              type="primary"
              class="export-module-btn"
              @click="exportData"
              :loading="exportLoading"
              :icon="Download"
          >
            {{ t('enterprise.export.data') }}
          </el-button>
        </div>

        <!-- 主内容区域 - 左侧筛选器 + 右侧卡片列表 -->
        <div class="enterprise-main">
          <!-- 左侧筛选器，添加固定效果 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters" class="reset-filter-btn">
                  {{ t('enterprise.reset.filters') }}
                </el-button>
              </div>

              <!-- 根据字段设计筛选条件 -->
              <!-- 城市筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.city }">
                <div class="filter-header" @click="toggleFilter('city')">
                  <span>{{ t('enterprise.filter.city') }}</span>
                  <i :class="['el-icon', expanded.city ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.city" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.city }">
                    <el-input
                        v-model="citySearch"
                        :placeholder="t('enterprise.filter.city.placeholder')"
                        size="small"
                        clearable
                        @input="handleCitySearch"
                        prefix-icon="el-icon-search"
                    ></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.city">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('enterprise.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>

                  <el-checkbox :indeterminate="isIndeterminate.city" v-model="checkAll.city"
                               @change="handleCheckAllChange('city')">{{ t('enterprise.filter.all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.city" @change="handleFilterChange('city')">
                    <el-checkbox v-for="item in displayedCities"
                                 :key="item"
                                 :value="item">
                      {{ getFilterLabel('city', item) }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

              <!-- 州筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.state }">
                <div class="filter-header" @click="toggleFilter('state')">
                  <span>{{ t('enterprise.filter.state') }}</span>
                  <i :class="['el-icon', expanded.state ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.state" class="filter-content">
                  <div class="filter-search">
                    <el-input
                        v-model="queryParams.state"
                        :placeholder="t('enterprise.search.state')"
                        size="small"
                        clearable
                        @keyup.enter="fetchEnterprises"
                        prefix-icon="el-icon-search"
                    ></el-input>
                  </div>
                </div>

                <!-- 邮编筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.zipcode }">
                  <div class="filter-header" @click="toggleFilter('zipcode')">
                    <span>{{ t('enterprise.filter.zipcode') }}</span>
                    <i :class="['el-icon', expanded.zipcode ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.zipcode" class="filter-content">
                    <div class="filter-search">
                      <el-input
                          v-model="queryParams.zipcode"
                          :placeholder="t('enterprise.search.zipcode')"
                          size="small"
                          clearable
                          @keyup.enter="fetchEnterprises"
                          prefix-icon="el-icon-search"
                      ></el-input>
                    </div>
                  </div>
                </div>

                <!-- 行业筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.industry }">
                  <div class="filter-header" @click="toggleFilter('industry')">
                    <span>{{ t('enterprise.filter.industry') }}</span>
                    <i :class="['el-icon', expanded.industry ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.industry" class="filter-content">
                    <!-- 搜索框 -->
                    <div class="filter-search" :class="{ 'is-loading': esSearchLoading.industry }">
                      <el-input
                          v-model="industrySearch"
                          :placeholder="t('enterprise.filter.industry.placeholder')"
                          size="small"
                          clearable
                          @input="handleIndustrySearch"
                          prefix-icon="el-icon-search"
                      ></el-input>
                      <div class="filter-search-loading" v-if="esSearchLoading.industry">
                        <i class="el-icon-loading"></i>
                        <span>{{ t('enterprise.filter.loading', {}, '搜索中...') }}</span>
                      </div>
                    </div>

                    <el-checkbox :indeterminate="isIndeterminate.industry" v-model="checkAll.industry"
                                 @change="handleCheckAllChange('industry')">{{ t('enterprise.filter.all') }}
                    </el-checkbox>
                    <el-divider></el-divider>
                    <el-checkbox-group v-model="filters.industry" @change="handleFilterChange('industry')">
                      <el-checkbox v-for="item in displayedIndustries"
                                   :key="item"
                                   :value="item">
                        {{ getFilterLabel('industry', item) }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>

                <!-- 部门筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.department }">
                  <div class="filter-header" @click="toggleFilter('department')">
                    <span>{{ t('enterprise.filter.department') }}</span>
                    <i :class="['el-icon', expanded.department ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.department" class="filter-content">
                    <!-- 搜索框 -->
                    <div class="filter-search" :class="{ 'is-loading': esSearchLoading.department }">
                      <el-input
                          v-model="departmentSearch"
                          :placeholder="t('enterprise.filter.department.placeholder')"
                          size="small"
                          clearable
                          @input="handleDepartmentSearch"
                          prefix-icon="el-icon-search"
                      ></el-input>
                      <div class="filter-search-loading" v-if="esSearchLoading.department">
                        <i class="el-icon-loading"></i>
                        <span>{{ t('enterprise.filter.loading', {}, '搜索中...') }}</span>
                      </div>
                    </div>

                    <el-checkbox :indeterminate="isIndeterminate.department" v-model="checkAll.department"
                                 @change="handleCheckAllChange('department')">{{ t('enterprise.filter.all') }}
                    </el-checkbox>
                    <el-divider></el-divider>
                    <el-checkbox-group v-model="filters.department" @change="handleFilterChange('department')">
                      <el-checkbox v-for="item in displayedDepartments"
                                   :key="item"
                                   :value="item">
                        {{ getFilterLabel('department', item) }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>

                <!-- 职业筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.occupation }">
                  <div class="filter-header" @click="toggleFilter('occupation')">
                    <span>{{ t('enterprise.filter.occupation') }}</span>
                    <i :class="['el-icon', expanded.occupation ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.occupation" class="filter-content">
                    <!-- 搜索框 -->
                    <div class="filter-search" :class="{ 'is-loading': esSearchLoading.occupation }">
                      <el-input
                          v-model="occupationSearch"
                          :placeholder="t('enterprise.filter.occupation.placeholder')"
                          size="small"
                          clearable
                          @input="handleOccupationSearch"
                          prefix-icon="el-icon-search"
                      ></el-input>
                      <div class="filter-search-loading" v-if="esSearchLoading.occupation">
                        <i class="el-icon-loading"></i>
                        <span>{{ t('enterprise.filter.loading', {}, '搜索中...') }}</span>
                      </div>
                    </div>

                    <el-checkbox :indeterminate="isIndeterminate.occupation" v-model="checkAll.occupation"
                                 @change="handleCheckAllChange('occupation')">{{ t('enterprise.filter.all') }}
                    </el-checkbox>
                    <el-divider></el-divider>
                    <el-checkbox-group v-model="filters.occupation" @change="handleFilterChange('occupation')">
                      <el-checkbox v-for="item in displayedOccupations"
                                   :key="item"
                                   :value="item">
                        {{ getFilterLabel('occupation', item) }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>

                <!-- 员工规模筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.employee }">
                  <div class="filter-header" @click="toggleFilter('employee')">
                    <span>{{ t('enterprise.filter.employee') }}</span>
                    <i :class="['el-icon', expanded.employee ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.employee" class="filter-content">
                    <el-checkbox-group v-model="filters.employee" @change="handleEmployeeChange">
                      <el-checkbox :value="'0-20'">0-25</el-checkbox>
                      <el-checkbox :value="'20-50'">25-50</el-checkbox>
                      <el-checkbox :value="'50-100'">50-100</el-checkbox>
                      <el-checkbox :value="'100-500'">100-500</el-checkbox>
                      <el-checkbox :value="'500-1000'">500-1000</el-checkbox>
                      <el-checkbox :value="'1000-10000'">1000-10000</el-checkbox>
                      <el-checkbox :value="'10000+'">10000+</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>

                <!-- 收入规模筛选 -->
                <div class="filter-group" :class="{ expanded: expanded.reveneu }">
                  <div class="filter-header" @click="toggleFilter('reveneu')">
                    <span>{{ t('enterprise.filter.revenue') }}</span>
                    <i :class="['el-icon', expanded.reveneu ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.reveneu" class="filter-content">
                    <el-checkbox-group v-model="filters.reveneu" @change="handleReveneuChange">
                      <el-checkbox :value="'低于$1M'">< $1M</el-checkbox>
                      <el-checkbox :value="'$1M-$5M'">$1M-$5M</el-checkbox>
                      <el-checkbox :value="'$5M-$10M'">$5M-$10M</el-checkbox>
                      <el-checkbox :value="'$10M-$25M'">$10M-$25M</el-checkbox>
                      <el-checkbox :value="'$25M-$50M'">$25M-$50M</el-checkbox>
                      <el-checkbox :value="'$50M-$100M'">$50M-$100M</el-checkbox>
                      <el-checkbox :value="'$100M-$250M'">$100M-$250M</el-checkbox>
                      <el-checkbox :value="'$250M-$500M'">$250M-$500M</el-checkbox>
                      <el-checkbox :value="'$500M-$1B'">$500M-$1B</el-checkbox>
                      <el-checkbox :value="'$1B以上'">$1B +</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>

                <div class="filter-group" :class="{ expanded: expanded.contact }">
                  <div class="filter-header" @click="toggleFilter('contact')">
                    <span>{{ t('enterprise.filter.contact') }}</span>
                    <i :class="['el-icon', expanded.contact ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                  <div v-show="expanded.contact" class="filter-content">
                    <el-checkbox-group v-model="filters.contact" @change="handleContactChange">
                      <el-checkbox value="phone">{{ t('enterprise.filter.contact.phone') }}</el-checkbox>
                      <el-checkbox value="mobile">{{ t('enterprise.filter.contact.mobile') }}</el-checkbox>
                      <el-checkbox value="email">{{ t('enterprise.filter.contact.email') }}</el-checkbox>
                      <el-checkbox value="website">{{ t('enterprise.filter.contact.website') }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 企业列表 -->
            <div v-loading="loading" class="enterprise-card-list">
              <!-- 无数据提示 -->
              <div v-if="!loading && filteredEnterprises.length === 0" class="no-data">
                <i class="el-icon-warning-outline"></i>
                <p>{{ t('enterprise.no.data') }}</p>
                <el-button v-if="!hasSearched" type="primary" @click="handleLogin" class="login-btn">
                  {{ t('enterprise.login.to.access') }}
                </el-button>
              </div>

              <!-- 骨架屏 -->
              <div v-if="loading && filteredEnterprises.length === 0" class="skeleton-loading">
                <div v-for="i in 6" :key="i" class="skeleton-card">
                  <div class="skeleton-header">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-title"></div>
                  </div>
                  <div class="skeleton-content">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                  </div>
                </div>
              </div>

              <!-- 企业卡片 -->
              <div
                  v-for="(enterprise, index) in paginatedEnterprises"
                  :key="index"
                  class="enterprise-card"
              >
                <!-- 卡片头部 - 只显示公司名称和头像 -->
                <div class="card-header">
                  <div class="company-info">
                    <div class="company-avatar">
                      <svg viewBox="0 0 100 100" class="cartoon-avatar">
                        <!-- 背景 -->
                        <rect width="100" height="100" rx="10" :fill="getAvatarColor(enterprise.companyName, 0.1)"/>

                        <!-- 根据公司名称生成不同的建筑形状 -->
                        <template v-if="getAvatarStyle(enterprise.companyName) === 'modern'">
                          <!-- 现代高楼样式 -->
                          <rect x="30" y="30" width="40" height="60" :fill="getAvatarColor(enterprise.companyName)"/>
                          <rect x="45" y="10" width="10" height="20" :fill="getAvatarColor(enterprise.companyName)"/>
                          <!-- 窗户 -->
                          <rect x="35" y="35" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="45" y="35" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="35" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="35" y="45" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="45" y="45" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="45" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="35" y="55" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="45" y="55" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="55" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="35" y="65" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="45" y="65" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="65" width="6" height="6" fill="#ffffff" opacity="0.8"/>
                        </template>

                        <template v-else-if="getAvatarStyle(enterprise.companyName) === 'classic'">
                          <!-- 经典建筑样式 -->
                          <rect x="25" y="40" width="50" height="50" :fill="getAvatarColor(enterprise.companyName)"/>
                          <!-- 屋顶 -->
                          <polygon :points="'25,40 50,15 75,40'" :fill="getAvatarColor(enterprise.companyName, 0.7)"/>
                          <!-- 门 -->
                          <rect x="45" y="70" width="10" height="20"
                                :fill="getAvatarColor(enterprise.companyName, 0.7)"/>
                          <!-- 窗户 -->
                          <rect x="32" y="50" width="10" height="10" fill="#ffffff" opacity="0.8"/>
                          <rect x="58" y="50" width="10" height="10" fill="#ffffff" opacity="0.8"/>
                        </template>

                        <template v-else-if="getAvatarStyle(enterprise.companyName) === 'tech'">
                          <!-- 科技公司样式 -->
                          <circle cx="50" cy="50" r="30" :fill="getAvatarColor(enterprise.companyName)"/>
                          <circle cx="50" cy="50" r="20" :fill="getAvatarColor(enterprise.companyName, 0.7)"
                                  stroke="#ffffff" stroke-width="2"/>
                          <circle cx="50" cy="50" r="10" :fill="getAvatarColor(enterprise.companyName, 0.9)"/>
                        </template>

                        <template v-else>
                          <!-- 默认样式 -->
                          <rect x="30" y="35" width="40" height="55" :fill="getAvatarColor(enterprise.companyName)"/>
                          <!-- 窗户 -->
                          <rect x="37" y="42" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="42" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                          <rect x="37" y="58" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="58" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                          <rect x="37" y="74" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                          <rect x="55" y="74" width="8" height="8" fill="#ffffff" opacity="0.8"/>
                        </template>

                        <!-- 公司首字母 -->
                        <text x="50" y="55" font-size="22" text-anchor="middle" fill="#ffffff" font-weight="bold">
                          {{ enterprise.companyName ? enterprise.companyName.charAt(0).toUpperCase() : '?' }}
                        </text>
                      </svg>
                    </div>
                    <div class="company-name">{{ enterprise.companyName || t('enterprise.unknown') }}</div>
                  </div>
                  <div class="detail-button">
                    <el-button type="primary" @click="toggleEnterpriseDetails(enterprise)" class="detail-btn">
                      {{ enterprise.expanded ? t('enterprise.detail.collapse') : t('enterprise.detail.expand') }}
                    </el-button>
                  </div>
                </div>

                <!-- 基本信息区域 - 始终显示 -->
                <div class="card-basic-info">
                  <div class="basic-info-grid">
                    <div class="info-row">
                      <!-- 国家字段 - 已注释
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.country') }}</span>
                        <span class="info-value single-line">
                          <img
                            :src="getCountryFlag(enterprise.country)"
                            class="country-flag"
                            @error="handleFlagError"
                            alt=""
                          />
                          {{ enterprise.country || '-' }}
                        </span>
                      </div>
                      -->
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.city') }}</span>
                        <span class="info-value single-line">{{ enterprise.primaryCity || '-' }}</span>
                      </div>
                    </div>
                    <div class="info-row">
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.industry') }}</span>
                        <span class="info-value single-line">{{ enterprise.industry || '-' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.subindustry') }}</span>
                        <span class="info-value single-line">{{ enterprise.subIndustry || '-' }}</span>
                      </div>
                    </div>
                    <div class="info-row">
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.employee') }}</span>
                        <span class="info-value single-line">{{ enterprise.employee || '-' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">{{ t('enterprise.info.revenue') }}</span>
                        <span class="info-value single-line">{{ enterprise.reveneu || '-' }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 详细内容 - 点击详情后显示 -->
                <div class="card-content" v-if="enterprise.expanded">
                  <div class="detail-title">{{ t('enterprise.detail.title') }}</div>
                  <!-- 企业详细信息 -->
                  <div class="info-table-wrapper">
                    <table class="info-table">
                      <tbody>
                      <tr>
                        <td class="label-cell">{{ t('enterprise.info.contact') }}</td>
                        <td class="value-cell single-line">{{
                            (enterprise.firstName || '') + ' ' + (enterprise.middleName || '') + ' ' + (enterprise.lastName || '')
                          }}</td>
                        <td class="label-cell">{{ t('enterprise.info.position') }}</td>
                        <td class="value-cell single-line">{{ enterprise.title || '-' }}</td>
                      </tr>
                      <tr>
                        <td class="label-cell">{{ t('enterprise.info.phone') }}</td>
                        <td class="value-cell">
                          <el-tooltip
                              v-if="enterprise.phone && enterprise.phone.includes('*')"
                              :content="t('enterprise.detail.view.tip', {}, '点击查看详细信息（消耗1次查询次数）')"
                              placement="top"
                              effect="dark"
                          >
                    <span
                        class="masked-info"
                        @click="viewDetailInfo(enterprise, 'phone')">
                        {{ enterprise.phone }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                    </span>
                          </el-tooltip>
                          <span v-else>{{ enterprise.phone || '-' }}</span>
                        </td>
                        <!-- 添加移动电话字段 -->
                        <td class="label-cell">{{ t('enterprise.info.mobile') }}</td>
                        <td class="value-cell">
                          <el-tooltip
                              v-if="enterprise.mobile && enterprise.mobile.includes('*')"
                              :content="t('enterprise.detail.view.tip', {}, '点击查看详细信息（消耗1次查询次数）')"
                              placement="top"
                              effect="dark"
                          >
                    <span
                        class="masked-info"
                        @click="viewDetailInfo(enterprise, 'mobile')">
                        {{ enterprise.mobile }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                    </span>
                          </el-tooltip>
                          <span v-else>{{ enterprise.mobile || '-' }}</span>
                        </td>
                      </tr>
                      <tr>
                        <td class="label-cell">{{ t('enterprise.info.email') }}</td>
                        <td class="value-cell">
                          <el-tooltip
                              v-if="enterprise.email && enterprise.email.includes('*')"
                              :content="t('enterprise.detail.view.tip', {}, '点击查看详细信息（消耗1次查询次数）')"
                              placement="top"
                              effect="dark"
                          >
                    <span
                        class="masked-info"
                        @click="viewDetailInfo(enterprise, 'email')">
                        {{ enterprise.email }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                    </span>
                          </el-tooltip>
                          <span v-else>{{ enterprise.email || '-' }}</span>
                        </td>
                        <td class="label-cell">{{ t('enterprise.info.website') }}</td>
                        <td class="value-cell url-cell">
                          <el-tooltip
                              v-if="enterprise.webAddress && enterprise.webAddress.includes('*')"
                              :content="t('enterprise.detail.view.tip', {}, '点击查看详细信息（消耗1次查询次数）')"
                              placement="top"
                              effect="dark"
                          >
                    <span
                        class="masked-info"
                        @click="viewDetailInfo(enterprise, 'website')">
                        {{ enterprise.webAddress }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                    </span>
                          </el-tooltip>
                          <a v-else-if="enterprise.webAddress" :href="addHttpPrefix(enterprise.webAddress)"
                             target="_blank">{{ enterprise.webAddress }}</a>
                          <span v-else>-</span>
                        </td>
                      </tr>
                      <tr class="address-row">
                        <td class="label-cell">{{ t('enterprise.info.address') }}</td>
                        <td class="value-cell address-cell" colspan="1">
                          {{ enterprise.mailingAddress || '-' }}
                        </td>
                        <td class="label-cell">{{ t('enterprise.info.department') }}</td>
                        <td class="value-cell single-line">{{ enterprise.department || '-' }}</td>
                        <td class="label-cell"></td>
                        <td class="value-cell"></td>
                      </tr>
                      <tr>
                        <td class="label-cell">{{ t('enterprise.info.state') }}</td>
                        <td class="value-cell single-line">{{ enterprise.primaryState || '-' }}</td>
                        <td class="label-cell">{{ t('enterprise.info.zipcode') }}</td>
                        <td class="value-cell single-line">{{ enterprise.zipCode || '-' }}</td>
                      </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="sizes, prev, pager, next, jumper"
                  :total="paginationTotal"
                  :pager-count="5"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 导出对话框 -->
  <el-dialog
      v-model="exportDialogVisible"
      :title="t('enterprise.export.dialog.title')"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('enterprise.export.matching.records') }} <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>{{ t('enterprise.export.balance') }} <span class="export-highlight">{{
            userBalance.exportQuotaRemaining
          }}</span></p>
        <p class="export-note">{{ t('enterprise.export.note') }}</p>
      </div>

      <!-- 字段选择区域 -->
      <div class="field-selection">
        <div class="field-selection-header">
          <h4>{{ t('export.selectFields') }}</h4>
          <div class="field-selection-actions">
            <el-button
                size="small"
                @click="selectAllFields"
                :disabled="isAllFieldsSelected"
            >
              {{ t('export.selectAll') }}
            </el-button>
            <el-button
                size="small"
                @click="selectNoFields"
                :disabled="isNoFieldsSelected"
            >
              {{ t('export.selectNone') }}
            </el-button>
          </div>
        </div>

        <div class="field-selection-content">
          <div class="field-grid">
            <div
                v-for="field in allFields"
                :key="field.key"
                class="field-item"
            >
              <el-checkbox
                  v-model="field.selected"
                  @change="updateSelectedFields"
              >
                <span :class="{ 'field-unselected': !field.selected }">
                  {{ t(field.labelKey) }}
                </span>
              </el-checkbox>
            </div>
          </div>

          <div v-if="isNoFieldsSelected" class="field-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.noFieldsSelected') }}
          </div>
        </div>
      </div>

      <div class="export-input">
        <p>{{ t('enterprise.export.enter.count') }}</p>
        <el-input-number
            v-model="exportCount"
            :min="1"
            :max="Math.max(1, Math.min(totalMatchCount.value, 50000, userBalance.exportQuotaRemaining || 1))"
            :step="100"
            size="large"
            controls-position="right"
        />

        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('enterprise.export.error.exceed') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('enterprise.export.error.balance') }}
          </p>
          <!--          <p v-if="isExportLimitExceeded" class="export-warning">-->
          <!--            <i class="el-icon-warning-outline"></i>-->
          <!--            {{ t('enterprise.export.error.limit') }}-->
          <!--          </p>-->
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('enterprise.cancel') }}</el-button>
        <el-button
            type="primary"
            @click="doExport"
            :loading="exportLoading"
            :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount || isNoFieldsSelected"
        >
          {{ t('enterprise.export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {ref, reactive, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Download, Check, WarningFilled, Refresh, Lock} from '@element-plus/icons-vue'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import request from '@/utils/request'
import {
  exportGlobalEnterprises,
  getGlobalEnterprisesCount,
  getUserBalanceInfo,
  searchCitiesFromES,
  searchIndustriesFromES,
  searchDepartmentsFromES,
  searchOccupationsFromES
} from '@/api/enterprise'
import {
  t as translate,
  getCurrentLanguage,
  currentLanguage as globalCurrentLanguage,
  addTranslation
} from '@/utils/i18n'

export default {
  name: 'GlobalEnterprise',
  components: {
    MainHeader,
    SideMenu,
    Download,
    Check,
    WarningFilled,
    Refresh,
    Lock
  },
  setup() {
    // 定义一个支持默认值的t函数
    const t = (key, params = {}, defaultValue = key) => {
      const translation = translate(key, params);
      return translation === key ? defaultValue : translation;
    };

    // 提供Download图标给模板使用
    const iconDownload = Download;

    const loading = ref(false)
    const enterprises = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalEnterprise = ref(0)
    const realTotalEnterprise = ref(0) // 真实的数据总量
    const hasSearched = ref(false)
    const exportLoading = ref(false)

    // 分页限制常量（设置只显示前10000条数据）
    const MAX_RESULT_WINDOW = 10000 // 限制为10000条
    const MAX_PAGINATION_RECORDS = MAX_RESULT_WINDOW // 最大分页记录数：1万条

    // 添加详情查看相关状态
    const detailViewLoading = ref(false)

    // 导出相关的状态
    const exportDialogVisible = ref(false)
    const totalMatchCount = ref(0)
    const exportCount = ref(0)
    const userBalance = ref({
      exportQuotaRemaining: 0
    })

    // 字段选择相关变量
    const selectedFields = ref([]);
    // 使用全局响应式语言变量，确保语言切换时实时更新
    const currentLanguage = globalCurrentLanguage;

    // 创建国际化字段配置
    const createFieldsConfig = () => {
      return [
        {key: 'companyName', labelKey: 'globalEnterprise.field.companyName', selected: true},
        // 注释掉国家字段选项
        // { key: 'country', labelKey: 'globalEnterprise.field.country', selected: true },
        {key: 'primaryCity', labelKey: 'globalEnterprise.field.city', selected: true},
        {key: 'primaryState', labelKey: 'globalEnterprise.field.province', selected: true},
        {key: 'industry', labelKey: 'globalEnterprise.field.industry', selected: true},
        {key: 'subIndustry', labelKey: 'globalEnterprise.field.subIndustry', selected: true},
        {key: 'employee', labelKey: 'globalEnterprise.field.employee', selected: true},
        {key: 'reveneu', labelKey: 'globalEnterprise.field.revenue', selected: true},
        {key: 'firstName', labelKey: 'linkedin.field.firstName', selected: true},
        // { key: 'middleName', labelKey: 'linkedin.field.firstName', selected: false },
        {key: 'lastName', labelKey: 'linkedin.field.lastName', selected: true},
        {key: 'title', labelKey: 'linkedin.field.headline', selected: true},
        {key: 'phone', labelKey: 'globalEnterprise.field.phone', selected: true},
        {key: 'mobile', labelKey: 'globalEnterprise.field.mobile', selected: true},
        {key: 'email', labelKey: 'globalEnterprise.field.email', selected: true},
        {key: 'mailingAddress', labelKey: 'globalEnterprise.field.address', selected: true},
        {key: 'zipCode', labelKey: 'linkedin.field.zipcode', selected: false},
        {key: 'webAddress', labelKey: 'globalEnterprise.field.website', selected: true}
      ];
    };

    const allFields = ref(createFieldsConfig());
    const isExportCountExceeded = computed(() => {
      return exportCount.value > totalMatchCount.value
    })
    const isBalanceInsufficient = computed(() => {
      return exportCount.value > userBalance.value.exportQuotaRemaining
    })
    const isExportLimitExceeded = computed(() => {
      return exportCount.value > 50000
    })

    // 字段选择相关函数
    const initSelectedFields = () => {
      selectedFields.value = allFields.value.filter(field => field.selected).map(field => field.key);
    };

    const updateSelectedFields = () => {
      const newSelectedFields = allFields.value.filter(field => field.selected).map(field => field.key);
      selectedFields.value = newSelectedFields;
    };

    const selectAllFields = () => {
      allFields.value.forEach(field => {
        field.selected = true;
      });
      updateSelectedFields();
    };

    const selectNoFields = () => {
      allFields.value.forEach(field => {
        field.selected = false;
      });
      updateSelectedFields();
    };

    const isAllFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => field.selected);
      return result;
    });

    const isNoFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => !field.selected);
      return result;
    });

    // 查询参数
    const queryParams = reactive({
      companyName: '',
      lastName: '',
      firstName: '',
      zipcode: ''
    })

    // 筛选器展开状态
    const expanded = reactive({
      city: true,
      industry: true,
      employee: true,
      reveneu: true,
      contact: true,
      department: true,
      occupation: true,
      zipcode: true,
      state: true
    })

    // 全选状态
    const checkAll = reactive({
      city: false,
      country: false,
      industry: false,
      department: false,
      occupation: false
    })

    // 是否半选状态
    const isIndeterminate = reactive({
      city: false,
      country: false,
      industry: false,
      department: false,
      occupation: false
    })

    // 筛选条件
    const filters = reactive({
      city: [],
      country: [],
      industry: [],
      employee: [],
      reveneu: [],
      department: [],
      occupation: [],
      contact: []
    })

    // 筛选器搜索关键词
    const countrySearch = ref('')
    const citySearch = ref('')
    const industrySearch = ref('')
    const departmentSearch = ref('')
    const occupationSearch = ref('')

    // 存储ES查询结果
    const esCities = ref([])
    const esIndustries = ref([])
    const esDepartments = ref([])
    const esOccupations = ref([])
    const esSearchLoading = ref({
      city: false,
      industry: false,
      department: false,
      occupation: false
    })

    // 切换筛选器展开状态
    const toggleFilter = (filter) => {
      expanded[filter] = !expanded[filter]
    }

    // 处理全选/取消全选
    const handleCheckAllChange = (field) => {
      if (checkAll[field]) {
        // 全选
        const options = getOptionsForField(field)
        filters[field] = [...options]
      } else {
        // 取消全选
        filters[field] = []
      }
      isIndeterminate[field] = false

      // 重新获取数据
      currentPage.value = 1 // 重置到第一页
      fetchEnterprises()
    }

    // 监听筛选条件变化
    const handleFilterChange = (field) => {
      const options = getOptionsForField(field)

      if (filters[field].length === 0) {
        checkAll[field] = false
        isIndeterminate[field] = false
      } else if (filters[field].length === options.length) {
        checkAll[field] = true
        isIndeterminate[field] = false
      } else {
        checkAll[field] = false
        isIndeterminate[field] = true
      }

      // 重新获取数据
      currentPage.value = 1 // 重置到第一页
      fetchEnterprises()
    }

    // 重置公司名称搜索
    const resetCompanySearch = () => {
      queryParams.companyName = ''
      currentPage.value = 1 // 重置到第一页
      fetchEnterprises()
    }

    // 重置所有筛选条件
    const resetAllFilters = () => {
      // 重置查询参数
      queryParams.companyName = ''
      queryParams.lastName = ''
      queryParams.firstName = ''
      queryParams.zipcode = ''
      queryParams.state = ''

      // 重置所有筛选条件
      Object.keys(filters).forEach(key => {
        filters[key] = []
        checkAll[key] = false
        isIndeterminate[key] = false
      })

      // 重置搜索关键词
      countrySearch.value = ''
      citySearch.value = ''
      industrySearch.value = ''
      departmentSearch.value = ''
      occupationSearch.value = ''

      // 重置ES搜索结果
      esCities.value = []
      esIndustries.value = []
      esDepartments.value = []
      esOccupations.value = []

      currentPage.value = 1 // 重置到第一页
      fetchEnterprises()
    }

    // 筛选后的国家列表
    const filteredCountries = computed(() => {
      // 先获取数据库中的实际国家，确保它们排在前面
      const dbCountries = [...new Set(enterprises.value.map(item => item.country).filter(Boolean))];

      // 添加其他国家作为额外选项
      const additionalCountries = [
        'USA', 'China', 'Japan', 'United Kingdom', 'Germany', 'France', 'Canada', 'Australia',
        'India', 'Brazil', 'Russia', 'South Korea', 'Italy', 'Spain', 'Mexico', 'Indonesia',
        'Netherlands', 'Saudi Arabia', 'Switzerland', 'Turkey', 'Taiwan', 'Sweden', 'Poland',
        'Belgium', 'Thailand', 'Ireland', 'Austria', 'Norway', 'United Arab Emirates', 'Israel',
        'Denmark', 'Singapore', 'Malaysia', 'Hong Kong', 'Philippines', 'Vietnam'
      ].filter(country => !dbCountries.includes(country)); // 过滤掉已存在的

      // 合并数组，确保数据库国家排在前面
      const allCountries = [...dbCountries, ...additionalCountries];

      if (!countrySearch.value) return allCountries;
      return allCountries.filter(country =>
          country.toLowerCase().includes(countrySearch.value.toLowerCase())
      );
      if (!citySearch.value) return allCountries;
      return allCountries.filter(country =>
          country.toLowerCase().includes(countrySearch.value.toLowerCase())
      );
    })

    // 添加行业的中英文翻译
    const industryTranslations = {
      'Services-Computer Programming Services': {zh: '计算机编程服务', en: 'Services-Computer Programming Services'},
      'Services-Offices & Clinics Of Doctors Of Medicine': {
        zh: '医生诊所和医疗服务',
        en: 'Services-Offices & Clinics Of Doctors Of Medicine'
      },
      'National Commercial Banks': {zh: '国家商业银行', en: 'National Commercial Banks'},
      'Real Estate Agents & Managers (For Others)': {
        zh: '房地产代理和管理',
        en: 'Real Estate Agents & Managers (For Others)'
      },
      'Services-Management Consulting Services': {zh: '管理咨询服务', en: 'Services-Management Consulting Services'},
      'Services-Employment Agencies': {zh: '就业服务机构', en: 'Services-Employment Agencies'},
      'Retail-Eating Places': {zh: '餐饮零售', en: 'Retail-Eating Places'},
      'Wholesale-Durable Goods': {zh: '耐用商品批发', en: 'Wholesale-Durable Goods'},
      'Services-Legal Services': {zh: '法律服务', en: 'Services-Legal Services'},
      'Television Broadcasting Stations': {zh: '电视广播站', en: 'Television Broadcasting Stations'},
      'Pharmaceutical Preparations': {zh: '药物制剂', en: 'Pharmaceutical Preparations'},
      'Services-Engineering Services': {zh: '工程服务', en: 'Services-Engineering Services'},
      'Industrial Machinery And Equipment': {zh: '工业机械和设备', en: 'Industrial Machinery And Equipment'},
      'Retail-Grocery Stores': {zh: '杂货零售', en: 'Retail-Grocery Stores'},
      'Hotels & Motels': {zh: '酒店和汽车旅馆', en: 'Hotels & Motels'},
      'Services-Child Day Care Services': {zh: '儿童日托服务', en: 'Services-Child Day Care Services'},
      'Services-Commercial Physical & Biological Research': {
        zh: '商业物理和生物研究',
        en: 'Services-Commercial Physical & Biological Research'
      },
      'Services-Prepackaged Software': {zh: '预包装软件服务', en: 'Services-Prepackaged Software'},
      'Investment Advice': {zh: '投资建议', en: 'Investment Advice'},
      'Architectural Services': {zh: '建筑服务', en: 'Architectural Services'},
      'Retail-Department Stores': {zh: '百货商店零售', en: 'Retail-Department Stores'},
      'Services-Management Services': {zh: '管理服务', en: 'Services-Management Services'},
      'Direct Selling Establishments': {zh: '直销机构', en: 'Direct Selling Establishments'},
      'Entertainers & Entertainment Groups': {zh: '娱乐人员和娱乐团体', en: 'Entertainers & Entertainment Groups'},
      'Services-Medical Laboratories': {zh: '医学实验室服务', en: 'Services-Medical Laboratories'},
      'Services-Health Services': {zh: '健康服务', en: 'Services-Health Services'},
      'Services-Computer Processing & Data Preparation': {
        zh: '计算机处理和数据准备服务',
        en: 'Services-Computer Processing & Data Preparation'
      }
    };

    // 为每个行业添加翻译
    const addIndustryTranslations = () => {
      Object.keys(industryTranslations).forEach(industry => {
        const translations = industryTranslations[industry];
        addTranslation(`industry.${industry}`, {
          zh: translations.zh,
          en: translations.en
        });
      });
    };

    // 不需要这个变量了，已直接修改onMounted函数

    // 筛选后的行业列表
    const filteredIndustries = computed(() => {
      // 使用硬编码的行业列表，不再从数据中获取
      const predefinedIndustries = Object.keys(industryTranslations);

      // 根据搜索关键词筛选（支持中英文搜索）
      if (!industrySearch.value) return predefinedIndustries;

      const currentLang = getCurrentLanguage();
      return predefinedIndustries.filter(industry => {
        // 获取当前语言下的行业名称
        const translatedName = currentLang === 'zh' ?
            industryTranslations[industry].zh :
            industryTranslations[industry].en;

        // 同时搜索英文原名和翻译后的名称
        return industry.toLowerCase().includes(industrySearch.value.toLowerCase()) ||
            translatedName.toLowerCase().includes(industrySearch.value.toLowerCase());
      });
    });

    // 合并显示：确保已选项始终可见（行业）
    const displayedIndustries = computed(() => {
      const set = new Set(filteredIndustries.value)
      esIndustries.value.forEach((i) => set.add(i))
      ;(filters.industry || []).forEach((i) => set.add(i))
      return Array.from(set)
    })

    // 合并显示：确保已选项始终可见（部门）
    const displayedDepartments = computed(() => {
      const set = new Set(filteredDepartments.value)
      esDepartments.value.forEach((i) => set.add(i))
      ;(filters.department || []).forEach((i) => set.add(i))
      return Array.from(set)
    })

    // 合并显示：确保已选项始终可见（职业）
    const displayedOccupations = computed(() => {
      const set = new Set(filteredOccupations.value)
      esOccupations.value.forEach((i) => set.add(i))
      ;(filters.occupation || []).forEach((i) => set.add(i))
      return Array.from(set)
    })

    // 过滤后的企业列表
    const filteredEnterprises = computed(() => {
      // 由于过滤现在在后端完成，直接返回enterprises
      return enterprises.value
    })

    // 分页后的企业列表
    const paginatedEnterprises = computed(() => {
      // 如果已经从后端获取了分页数据，则直接使用企业列表
      return filteredEnterprises.value
    })

    // 修改maxSafePage的计算逻辑，使总数据量上限为10000条
    const MAX_DATA_LIMIT = 10000 // 定义最大数据限制为10000条

    // 计算最大安全页码，限制数据量为10000条
    const maxSafePage = computed(() => {
      // 根据pageSize计算对应的10000条数据的最大页数
      return Math.ceil(MAX_DATA_LIMIT / pageSize.value)
    })

    // 计算分页显示的总数（基于10000条数据限制）
    const paginationTotal = computed(() => {
      const realTotal = realTotalEnterprise.value || totalEnterprise.value
      // 限制最大记录数为10000条
      return Math.min(realTotal, MAX_DATA_LIMIT)
    })

    // 检查是否超过分页限制（总数>MAX_DATA_LIMIT）
    const isPaginationLimited = computed(() => {
      const realTotal = realTotalEnterprise.value || totalEnterprise.value
      return realTotal > MAX_DATA_LIMIT
    })

    // 分页限制提示信息可以保留但不展示
    const paginationLimitMessage = computed(() => {
      return ''
    })

    // 返回筛选项显示标签（优先使用翻译字典，无则用原文）
    const getFilterLabel = (type, value) => {
      if (!value) return ''
      const lang = (typeof getCurrentLanguage === 'function' ? getCurrentLanguage() : 'en') || 'en'
      const dicts = {
        city: cityTranslations,
        industry: industryTranslations,
        department: departmentTranslations,
        occupation: occupationTranslations
      }
      const dict = dicts[type] || {}
      const entry = dict[value]
      if (entry && typeof entry === 'object') {
        return lang === 'zh' ? (entry.zh || value) : (entry.en || value)
      }
      return value
    }

    // 格式化显示的总企业数量，当数量>=10000时添加"+"号
    const formattedTotalEnterprise = computed(() => {
      const total = totalEnterprise.value
      return total >= 10000 ? `${total}+` : total.toString()
    })

    // 获取企业数据
    const fetchEnterprises = async () => {
      loading.value = true
      hasSearched.value = true

      try {
        let url = '/enterprises/global'

        // 当有任何筛选条件时使用search端点
        if (queryParams.companyName ||
            queryParams.lastName ||
            queryParams.firstName ||
            queryParams.zipcode ||
            queryParams.state ||
            filters.city.length > 0 ||
            filters.industry.length > 0 ||
            filters.employee.length > 0 ||
            filters.department.length > 0 ||
            filters.occupation.length > 0 ||
            filters.reveneu.length > 0 ||
            filters.contact.length > 0) {
          url = '/enterprises/global/search'
        }

        // 构建查询参数，包含分页信息
        const params = {
          page: currentPage.value,
          size: pageSize.value
        }

        if (queryParams.companyName) {
          params.companyName = queryParams.companyName
        }

        if (queryParams.lastName) {
          params.lastName = queryParams.lastName
        }

        if (queryParams.firstName) {
          params.firstName = queryParams.firstName
        }

        if (queryParams.zipcode) {
          params.zipcode = queryParams.zipcode
        }

        if (queryParams.state) {
          params.state = queryParams.state
        }

        // 添加筛选条件 - 普通搜索使用逗号分隔的字符串
        if (filters.country.length > 0) {
          params.country = filters.country.join(',')
        }

        if (filters.city.length > 0) {
          params.city = filters.city.join(',')
        }

        if (filters.industry.length > 0) {
          params.industry = filters.industry.join(',')
        }

        if (filters.department.length > 0) {
          params.department = filters.department.join(',')
        }

        if (filters.occupation.length > 0) {
          params.occupation = filters.occupation.join(',')
        }

        if (filters.employee.length > 0) {
          params.employee = filters.employee.join(',')
        }

        if (filters.reveneu.length > 0) {
          params.reveneu = filters.reveneu.join(',')
        }

        if (filters.contact.length > 0) {
          params.hasContact = filters.contact.join(',')
        }

        const response = await request.get(url, {params})

        if (response.code === 200 && response.data) {
          // 适配新的响应数据格式
          if (response.data.records && Array.isArray(response.data.records)) {
            // 新格式：包含分页信息和records数组
            const responseTotal = response.data.total || 0
            const responseRealCount = response.data.realCount || responseTotal

            // 保存真实的数据总量
            realTotalEnterprise.value = responseRealCount

            // 设置分页显示的总数（限制最大10000条）
            totalEnterprise.value = Math.min(responseRealCount, MAX_PAGINATION_RECORDS)

            currentPage.value = response.data.current || 1
            pageSize.value = response.data.size || 10

            // 将数据映射并添加expanded属性
            enterprises.value = response.data.records.map(enterprise => ({
              ...enterprise,
              expanded: false
            }))
          } else if (Array.isArray(response.data)) {
            // 旧格式：直接是数组
            enterprises.value = response.data.map(enterprise => ({
              ...enterprise,
              expanded: false
            }))
          } else {
            throw new Error('返回数据格式不正确')
          }
        } else {
          const msg = response.msg || ''
          // 如果后端返回余额不足，参照 CantonFairExhibitors 的做法：仅重置到第一页
          if (msg.includes('余额不足')) {
            if (currentPage.value !== 1) {
              currentPage.value = 1
            }
            return
          }
          throw new Error(msg || '获取数据失败')
        }
      } catch (error) {
        // 捕获异常时也判断是否余额不足，参照 CantonFairExhibitors：仅重置到第一页
        try {
          const errMsg = (error && (error.response?.data?.message || error.message)) || ''
          if (errMsg.includes('余额不足')) {
            if (currentPage.value !== 1) {
              currentPage.value = 1
            }
            return
          }
        } catch (_) { /* 忽略解析错误 */
        }

        ElMessage.error('获取企业数据失败，请稍后重试')
        enterprises.value = []
      } finally {
        loading.value = false
      }
    }

    // 切换企业详情展示
    const toggleEnterpriseDetails = (enterprise) => {
      enterprise.expanded = !enterprise.expanded
    }

    // 验证页码是否安全（不会触发ES错误）
    const validatePageSafety = (page, size) => {
      const from = (page - 1) * size
      const total = from + size
      return total <= MAX_RESULT_WINDOW
    }

    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size

      // 检查当前页码在新的页面大小下是否安全
      if (!validatePageSafety(currentPage.value, size)) {
        // 如果不安全，重置到第一页
        currentPage.value = 1
      }

      // 重新获取数据
      fetchEnterprises()
    }

    // 处理当前页变化
    const handleCurrentChange = (page) => {
      // 验证页码安全性
      if (!validatePageSafety(page, pageSize.value)) {
        const maxSafe = maxSafePage.value
        // 静默处理，不显示错误提示
        currentPage.value = maxSafe
        page = maxSafe
      } else {
        currentPage.value = page
      }



      // 重新获取数据
      fetchEnterprises()
    }

    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        // 先获取符合条件的记录数量
        await fetchExportCount()

        // 再获取用户余额
        await fetchUserBalance()

        // 显示导出对话框
        exportDialogVisible.value = true
      } catch (error) {
        ElMessage.error('准备导出失败，请稍后重试')
      } finally {
        exportLoading.value = false
      }
    }

    // 获取符合条件的记录数量
    const fetchExportCount = async () => {
      try {
        // 构建参数对象
        const params = {};

        if (queryParams.companyName) {
          params.companyName = queryParams.companyName;
        }

        // 添加筛选条件 - count接口需要使用逗号分隔的字符串
        if (filters.country.length > 0) {
          params.country = filters.country.join(',');
        }

        if (filters.city.length > 0) {
          params.city = filters.city.join(',');
        }

        if (filters.industry.length > 0) {
          params.industry = filters.industry.join(',');
        }

        if (filters.department.length > 0) {
          params.department = filters.department.join(',');
        }

        if (filters.occupation.length > 0) {
          params.occupation = filters.occupation.join(',');
        }

        if (filters.employee.length > 0) {
          params.employee = filters.employee.join(',');
        }

        if (filters.reveneu.length > 0) {
          params.reveneu = filters.reveneu.join(',');
        }

        if (filters.contact.length > 0) {
          params.hasContact = filters.contact.join(',')
        }

        const response = await getGlobalEnterprisesCount(params);

        if (response.code === 200) {
          const count = response.data.count || 0;

          totalMatchCount.value = count > 50000 ? 50000 : count;
          exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
          return count;
        } else {
          ElMessage.error(response.msg || '获取记录数量失败');
          return 0;
        }
      } catch (error) {
        ElMessage.error('获取记录数量失败，请稍后重试');
        return 0;
      }
    }

    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const response = await getUserBalanceInfo();
        if (response.code === 200 && response.data) {
          userBalance.value = response.data;
          return response.data;
        } else {
          ElMessage.error(response.msg || '获取余额信息失败');
          return {exportQuotaRemaining: 0};
        }
      } catch (error) {
        ElMessage.error('获取余额信息失败，请稍后重试');
        return {exportQuotaRemaining: 0};
      }
    }

    // 执行导出操作
    const doExport = async () => {
      // 检查字段选择
      if (isNoFieldsSelected.value) {
        ElMessage.error(t('export.error.noFieldsSelected'));
        return;
      }

      // 检查导出数量
      if (isExportCountExceeded.value) {
        ElMessage.error(t('export.error.countExceeded', {maxCount: totalMatchCount.value}));
        return;
      }

      // 检查导出上限
      if (isExportLimitExceeded.value) {
        ElMessage.error(t('export.error.limitExceeded'));
        return;
      }

      // 检查余额
      if (isBalanceInsufficient.value) {
        ElMessage.error(t('export.error.balanceInsufficient'));
        return;
      }

      // 确保导出数量是有效的数字
      if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
        ElMessage.error(t('export.error.invalidCount'));
        return;
      }

      exportLoading.value = true;
      try {
        // 准备导出参数对象
        const exportParams = {
          exportCount: Number(exportCount.value), // 确保转换为数字类型
          selectedFields: selectedFields.value.join(','), // 添加选中的字段列表
          language: currentLanguage.value // 添加当前语言参数
        };

        // 添加搜索条件
        if (queryParams.companyName) {
          exportParams.companyName = queryParams.companyName;
        }

        // 添加筛选条件
        if (filters.country.length > 0) {
          exportParams.country = filters.country;
        }

        if (filters.city.length > 0) {
          exportParams.city = filters.city;
        }

        if (filters.industry.length > 0) {
          exportParams.industry = filters.industry;
        }

        if (filters.department.length > 0) {
          exportParams.department = filters.department;
        }

        if (filters.occupation.length > 0) {
          exportParams.occupation = filters.occupation;
        }

        if (filters.employee.length > 0) {
          exportParams.employee = filters.employee;
        }

        if (filters.reveneu.length > 0) {
          exportParams.reveneu = filters.reveneu;
        }

        if (filters.contact.length > 0) {
          exportParams.hasContact = filters.contact.join(',')
        }

        // 显示开始导出的消息
        // ElMessage.info(t('export.loading.preparing'));

        // 提示用户导出正在处理
        ElMessage({
          message: t('export.loading.preparing'),
          type: 'info',
          duration: 3000
        });

        // 根据导出数据量大小显示不同提示
        if (exportCount.value > 10000 && exportCount.value <= 30000) {
          ElMessage({
            message: t('export.progress.processing'),
            type: 'warning',
            duration: 10000 // 显示10秒
          });
        } else if (exportCount.value > 30000) {
          // 大数据量导出，给用户更明确的等待提示
          ElMessageBox.alert(
              t('export.large.data.warning', {count: exportCount.value}),
              t('export.large.data.title'),
              {
                confirmButtonText: t('export.large.data.confirm'),
                type: 'warning',
                showClose: false
              }
          );
        }

        // 发送请求
        const response = await exportGlobalEnterprises(exportParams);

        // 检查响应是否为blob
        if (!response || !response.data) {
          throw new Error('导出失败：服务器未返回数据');
        }

        // 如果响应是正常JSON对象而不是Blob，可能是后端错误或成功消息
        if (!(response.data instanceof Blob)) {

          // 检查是否是成功的JSON响应
          if (response.data && response.data.code === 200) {
            ElMessage.error('导出失败：服务器配置错误，未返回Excel文件');
          } else if (response.data && response.data.message) {
            ElMessage.error(`导出失败：${response.data.message}`);
          } else if (response.data && response.data.msg) {
            ElMessage.error(`导出失败：${response.data.msg}`);
          } else {
            throw new Error('导出失败：服务器返回格式不正确');
          }

          // 无论如何，不能继续处理非Blob响应
          return;
        }

        // 获取Content-Type
        const contentType = response.headers && response.headers['content-type']
            ? response.headers['content-type']
            : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        // 检查是否是错误响应
        if (contentType.includes('json')) {
          // 可能是错误响应，尝试解析
          const reader = new FileReader();

          // 使用Promise包装FileReader
          const readJsonResponse = new Promise((resolve, reject) => {
            reader.onload = function () {
              try {
                const result = reader.result;
                const errorResponse = JSON.parse(result);
                resolve(errorResponse);
              } catch (e) {
                reject(new Error('导出失败：无法识别的错误'));
              }
            };
            reader.onerror = function (e) {
              reject(new Error('导出失败：无法读取错误响应'));
            };
          });

          reader.readAsText(response.data);

          try {
            const errorData = await readJsonResponse;
            // 显示具体的错误信息
            const errorMessage = errorData.msg || errorData.message || '未知错误';
            ElMessage.error(`导出失败：${errorMessage}`);

            // 如果错误与参数相关，可能需要提示用户修改导出数量
            if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
              ElMessage.warning('请检查导出数量是否正确设置');
            }

            return;
          } catch (e) {
            ElMessage.error(e.message || '导出失败：无法识别的错误');
            return;
          }
        }

        // 创建Blob对象
        const blob = new Blob([response.data], {type: contentType});

        // 获取文件名（支持国际化）
        const fileNamePrefix = currentLanguage.value === 'en' ? 'Global_Enterprise_Data' : '全球企业数据';
        let fileName = fileNamePrefix + '.xlsx';
        const disposition = response.headers && response.headers['content-disposition'];
        if (disposition && disposition.includes('filename=')) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '');
            try {
              fileName = decodeURIComponent(fileName);
            } catch (e) {

            }
          }
        }

        // 下载文件
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        // 关闭导出对话框
        exportDialogVisible.value = false;

        // 更新用户余额
        await fetchUserBalance();

        ElMessage.success(t('export.success.completed'));
      } catch (error) {

        ElMessage.error(t('export.error.failed'));
      } finally {
        exportLoading.value = false;
      }
    };

    // 获取国家旗帜图标
    const getCountryFlag = (country) => {
      if (!country) return 'https://flagcdn.com/w20/un.png';

      // 国家代码映射
      const countryCodeMap = {
        'USA': 'us',
        'United States': 'us',
        'China': 'cn',
        'India': 'in',
        'United Kingdom': 'gb',
        'UK': 'gb',
        'Canada': 'ca',
        'Germany': 'de',
        'France': 'fr',
        'Japan': 'jp',
        'Australia': 'au',
        'Brazil': 'br',
        'Singapore': 'sg',
        'Spain': 'es',
        'Italy': 'it',
        'Netherlands': 'nl',
        'Sweden': 'se',
        'Russia': 'ru',
        'Mexico': 'mx',
        'South Korea': 'kr',
        'Ireland': 'ie',
        'Switzerland': 'ch',
        'Philippines': 'ph'
      };

      const countryCode = countryCodeMap[country] || countryCodeMap[country.toLowerCase()];
      return countryCode ? `https://flagcdn.com/w20/${countryCode}.png` : 'https://flagcdn.com/w20/un.png';
    };

    // 处理国旗加载错误
    const handleFlagError = (e) => {
      // 设置默认国旗 (UN flag)
      e.target.src = 'https://flagcdn.com/w20/un.png';
    };

    // 格式化手机号（隐私保护）
    const getMaskedPhone = (phone) => {
      if (!phone) return ''
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }

    // 添加http前缀
    const addHttpPrefix = (url) => {
      if (!url) return ''
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      return 'http://' + url
    }

    // 登录以访问数据
    const handleLogin = async () => {
      try {
        // 跳转到登录页面
        const currentPath = window.location.pathname;
        window.location.href = `/login?redirect=${encodeURIComponent(currentPath)}`;
      } catch (error) {
        ElMessage.error('跳转登录页面失败，请稍后重试');
      }
    }

    // 获取企业头像颜色
    const getAvatarColor = (companyName, opacity = 1) => {
      if (!companyName) return `rgba(128, 128, 128, ${opacity})`

      // 使用公司名称的第一个字符的 ASCII 码作为种子
      const seed = companyName.charCodeAt(0)

      // 预定义一些好看的颜色
      const colors = [
        [66, 133, 244],   // Google Blue
        [219, 68, 55],    // Google Red
        [244, 180, 0],    // Google Yellow
        [15, 157, 88],    // Google Green
        [66, 133, 244],   // Microsoft Blue
        [129, 86, 214],   // Purple
        [242, 120, 75],   // Orange
        [0, 150, 136],    // Teal
        [121, 85, 72],    // Brown
        [96, 125, 139]    // Blue Grey
      ]

      // 选择颜色
      const color = colors[seed % colors.length]

      return `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${opacity})`
    }

    // 获取企业头像样式
    const getAvatarStyle = (companyName) => {
      if (!companyName) return 'default'

      // 根据公司名称的长度和特征选择不同的样式
      const nameLength = companyName.length
      const hasDigit = /\d/.test(companyName)
      const hasTechWord = /(tech|software|digital|cyber|data|ai|ml|cloud)/i.test(companyName)

      if (hasTechWord) {
        return 'tech'
      } else if (hasDigit || nameLength > 15) {
        return 'modern'
      } else {
        return 'classic'
      }
    }

    // 获取特定字段的所有选项
    const getOptionsForField = (field) => {
      switch (field) {
        case 'country':
          return filteredCountries.value
        case 'city':
          return filteredCities.value
        case 'industry':
          return filteredIndustries.value
        case 'department':
          return filteredDepartments.value
        case 'occupation':
          return filteredOccupations.value
        default:
          return []
      }
    }

    // 处理员工规模变化
    const handleEmployeeChange = () => {
      currentPage.value = 1
      fetchEnterprises()
    }

    // 处理收入规模变化
    const handleReveneuChange = () => {
      currentPage.value = 1
      fetchEnterprises()
    }

    const handleContactChange = () => {
      currentPage.value = 1
      fetchEnterprises()
    }

    // 添加查看详情信息的方法
    const viewDetailInfo = async (enterprise, infoType) => {
      try {
        const result = await ElMessageBox.confirm(
            t('enterprise.detail.confirm.message', {}, '查看详细信息将消耗1次查询次数，是否继续？'),
            t('enterprise.detail.confirm.title', {}, '确认查看'),
            {
              confirmButtonText: t('enterprise.detail.confirm.yes', {}, '确认'),
              cancelButtonText: t('enterprise.detail.confirm.no', {}, '取消'),
              type: 'warning'
            }
        )

        if (result === 'confirm') {
          detailViewLoading.value = true

          // 构建企业标识符，使用企业id
          const enterpriseId = enterprise.mtId
          const mt = enterprise.mt

          if (!enterpriseId) {
            throw new Error('企业ID不存在')
          }

          // 调用后端API查看详细信息
          const response = await request.get('/enterprises/global/detail', {
            params: {enterpriseId, mt}
          })

          if (response && response.code === 200 && response.data) {

            // 更新企业信息
            if (infoType === 'phone') {
              enterprise.phone = response.data.phone
            } else if (infoType === 'email') {
              enterprise.email = response.data.email
            } else if (infoType === 'website') {
              enterprise.webAddress = response.data.webAddress
            }else if (infoType === 'mobile') {
              enterprise.mobile = response.data.mobile
            }

            ElMessage.success(t('enterprise.detail.view.success', {}, '查看成功'))
          } else {
            throw new Error(response?.msg || t('enterprise.detail.view.error', {}, '查看失败'))
          }
        }
      } catch (error) {
        if (error === 'cancel') {
          // 用户取消，不做处理
          return
        }
        ElMessage.error(error.message || t('enterprise.detail.view.error', {}, '查看详情失败，请稍后重试'))
      } finally {
        detailViewLoading.value = false
      }
    }

    // 页面加载时获取数据
    onMounted(() => {
      // 添加行业翻译
      addIndustryTranslations();
      // 添加城市翻译
      addCityTranslations();
      // 添加部门翻译
      addDepartmentTranslations();
      // 添加职业翻译
      addOccupationTranslations();

      // 添加导出限制相关翻译
      addTranslation('export.error.limitExceeded', {
        zh: '导出数量超过系统限制，最多可导出50,000条记录',
        en: 'Export count exceeds system limit, maximum 50,000 records allowed'
      });

      // 添加ES搜索相关翻译
      addTranslation('enterprise.filter.es.results', {
        zh: '后端搜索结果',
        en: 'Backend Search Results'
      });

      addTranslation('enterprise.filter.loading', {
        zh: '搜索中...',
        en: 'Searching...'
      });

      // 添加部门筛选相关翻译
      addTranslation('enterprise.filter.department', {
        zh: '部门',
        en: 'Department'
      });

      // 添加邮编筛选相关翻译
      addTranslation('enterprise.filter.zipcode', {
        zh: '邮编',
        en: 'ZIP Code'
      });

      // 添加州筛选相关翻译
      addTranslation('enterprise.filter.state', {
        zh: '所在州',
        en: 'State'
      });

      addTranslation('enterprise.filter.department.placeholder', {
        zh: '搜索部门',
        en: 'Search departments'
      });

      // 添加职业筛选相关翻译
      addTranslation('enterprise.filter.occupation', {
        zh: '职业',
        en: 'Occupation'
      });

      addTranslation('enterprise.filter.occupation.placeholder', {
        zh: '搜索职业',
        en: 'Search occupations'
      });

      // 添加导出进度相关翻译
      addTranslation('export.progress.preparing', {
        zh: '正在准备导出数据，请耐心等待...',
        en: 'Preparing export data, please wait...'
      });

      addTranslation('export.progress.processing', {
        zh: '正在处理大量数据，可能需要较长时间，请勿关闭页面...',
        en: 'Processing large amount of data, this may take a while. Please don\'t close the page...'
      });

      addTranslation('export.loading.preparing', {
        zh: '正在准备导出数据...',
        en: 'Preparing data for export...'
      });

      addTranslation('export.large.data.title', {
        zh: '大数据量导出提示',
        en: 'Large Data Export Notice'
      });

      addTranslation('export.large.data.warning', {
        zh: '您正在导出{count}条记录，这是一个大型导出任务，可能需要1-3分钟才能完成。请保持网络连接并等待下载开始。',
        en: 'You are exporting {count} records. This is a large export task and may take 1-3 minutes to complete. Please maintain your network connection and wait for the download to start.'
      });

      addTranslation('export.large.data.confirm', {
        zh: '我已了解，开始导出',
        en: 'I understand, start export'
      });

      addTranslation('export.success.completed', {
        zh: '导出成功完成',
        en: 'Export completed successfully'
      });

      fetchEnterprises();
      // 初始化选中的字段
      initSelectedFields();
    })

    // 将以下代码添加到setup函数中，找到filteredCountries计算属性的位置后添加

    // 添加城市翻译
    const cityTranslations = {
      'New York': {zh: '纽约', en: 'New York'},
      'Los Angeles': {zh: '洛杉矶', en: 'Los Angeles'},
      'Chicago': {zh: '芝加哥', en: 'Chicago'},
      'San Francisco': {zh: '旧金山', en: 'San Francisco'},
      'Boston': {zh: '波士顿', en: 'Boston'},
      'Miami': {zh: '迈阿密', en: 'Miami'},
      'Seattle': {zh: '西雅图', en: 'Seattle'},
      'Houston': {zh: '休斯顿', en: 'Houston'},
      'Philadelphia': {zh: '费城', en: 'Philadelphia'},
      'Phoenix': {zh: '菲尼克斯', en: 'Phoenix'},
      'San Antonio': {zh: '圣安东尼奥', en: 'San Antonio'},
      'Dallas': {zh: '达拉斯', en: 'Dallas'},
      'Beijing': {zh: '北京', en: 'Beijing'},
      'Shanghai': {zh: '上海', en: 'Shanghai'},
      'Shenzhen': {zh: '深圳', en: 'Shenzhen'},
      'Guangzhou': {zh: '广州', en: 'Guangzhou'},
      'Chengdu': {zh: '成都', en: 'Chengdu'},
      'Chongqing': {zh: '重庆', en: 'Chongqing'},
      'Wuhan': {zh: '武汉', en: 'Wuhan'},
      'Xian': {zh: '西安', en: 'Xian'},
      'Hangzhou': {zh: '杭州', en: 'Hangzhou'},
      'Hong Kong': {zh: '香港', en: 'Hong Kong'},
      'Taipei': {zh: '台北', en: 'Taipei'},
      'Hsinchu': {zh: '新竹', en: 'Hsinchu'},
      'London': {zh: '伦敦', en: 'London'},
      'Birmingham': {zh: '伯明翰', en: 'Birmingham'},
      'Liverpool': {zh: '利物浦', en: 'Liverpool'},
      'Nottingham': {zh: '诺丁汉', en: 'Nottingham'},
      'Belfast': {zh: '贝尔法斯特', en: 'Belfast'},
      'Cambridge': {zh: '剑桥', en: 'Cambridge'},
      'Bath': {zh: '巴斯', en: 'Bath'},
      'Derby': {zh: '德比', en: 'Derby'},
      'Hounslow': {zh: '豪恩斯洛', en: 'Hounslow'},
      'Huddersfield': {zh: '哈德斯菲尔德', en: 'Huddersfield'},
      'Toronto': {zh: '多伦多', en: 'Toronto'},
      'Vancouver': {zh: '温哥华', en: 'Vancouver'},
      'Calgary': {zh: '卡尔加里', en: 'Calgary'},
      'Montreal': {zh: '蒙特利尔', en: 'Montreal'},
      'Halifax': {zh: '哈利法克斯', en: 'Halifax'},
      'Winnipeg': {zh: '温尼伯', en: 'Winnipeg'},
      'Mumbai': {zh: '孟买', en: 'Mumbai'},
      'New Delhi': {zh: '新德里', en: 'New Delhi'},
      'Bangalore': {zh: '班加罗尔', en: 'Bangalore'},
      'Delhi': {zh: '德里', en: 'Delhi'},
      'Hyderabad': {zh: '海得拉巴', en: 'Hyderabad'},
      'Ahmadabad': {zh: '艾哈迈达巴德', en: 'Ahmadabad'},
      'Dehradun': {zh: '德拉敦', en: 'Dehradun'},
      'Thiruvananthapuram': {zh: '特里凡得琅', en: 'Thiruvananthapuram'},
      'Noida': {zh: '诺伊达', en: 'Noida'},
      'Sydney': {zh: '悉尼', en: 'Sydney'},
      'Melbourne': {zh: '墨尔本', en: 'Melbourne'},
      'Adelaide': {zh: '阿德莱德', en: 'Adelaide'},
      'Hobart': {zh: '霍巴特', en: 'Hobart'},
      'Wollongong': {zh: '伍伦贡', en: 'Wollongong'},
      'Wagga Wagga': {zh: '沃加沃加', en: 'Wagga Wagga'},
      'Newcastle': {zh: '纽卡斯尔', en: 'Newcastle'},
      'Berlin': {zh: '柏林', en: 'Berlin'},
      // 'Cologne (Köln)': {zh: '科隆', en: 'Cologne (Köln)'},
      'Dortmund': {zh: '多特蒙德', en: 'Dortmund'},
      // 'Düsseldorf': {zh: '杜塞尔多夫', en: 'Düsseldorf'},
      'Hannover': {zh: '汉诺威', en: 'Hannover'},
      'Nuremberg': {zh: '纽伦堡', en: 'Nuremberg'},
      'Wiesbaden': {zh: '威斯巴登', en: 'Wiesbaden'},
      'Paris': {zh: '巴黎', en: 'Paris'},
      'Nice': {zh: '尼斯', en: 'Nice'},
      'Nantes': {zh: '南特', en: 'Nantes'},
      'Toulouse': {zh: '图卢兹', en: 'Toulouse'},
      'Tours': {zh: '图尔', en: 'Tours'},
      'Tokyo': {zh: '东京', en: 'Tokyo'},
      'Yokohama': {zh: '横滨', en: 'Yokohama'},
      'Nagoya': {zh: '名古屋', en: 'Nagoya'},
      'Naha': {zh: '那霸', en: 'Naha'},
      'Abu Dhabi': {zh: '阿布扎比', en: 'Abu Dhabi'},
      'Dubai': {zh: '迪拜', en: 'Dubai'},
      'Abuja': {zh: '阿布贾', en: 'Abuja'},
      'Accra': {zh: '阿克拉', en: 'Accra'},
      'Amsterdam': {zh: '阿姆斯特丹', en: 'Amsterdam'},
      'Den Haag': {zh: '海牙', en: 'Den Haag'},
      'Dublin': {zh: '都柏林', en: 'Dublin'},
      'Cape Town': {zh: '开普敦', en: 'Cape Town'},
      'Durban': {zh: '德班', en: 'Durban'},
      'Tel Aviv': {zh: '特拉维夫', en: 'Tel Aviv'},
      'Tel Aviv-Yafo': {zh: '特拉维夫-雅法', en: 'Tel Aviv-Yafo'},
      'Tallinn': {zh: '塔林', en: 'Tallinn'},
      'Zurich': {zh: '苏黎世', en: 'Zurich'},
      'Zug': {zh: '楚格', en: 'Zug'}
    };

    // 为每个城市添加翻译
    const addCityTranslations = () => {
      Object.keys(cityTranslations).forEach(city => {
        const translations = cityTranslations[city];
        addTranslation(`city.${city}`, {
          zh: translations.zh,
          en: translations.en
        });
      });
    };

    // 筛选后的城市列表
    const filteredCities = computed(() => {
      // 使用硬编码的城市列表
      const predefinedCities = Object.keys(cityTranslations);

      // 根据搜索关键词筛选（支持中英文搜索）
      if (!citySearch.value) return predefinedCities;

      const currentLang = getCurrentLanguage();
      return predefinedCities.filter(city => {
        // 获取当前语言下的城市名称
        const translatedName = currentLang === 'zh' ?
            cityTranslations[city].zh :
            cityTranslations[city].en;

        // 同时搜索英文原名和翻译后的名称
        return city.toLowerCase().includes(citySearch.value.toLowerCase()) ||
            translatedName.toLowerCase().includes(citySearch.value.toLowerCase());
      });
    });

    // 合并显示：确保已选项始终可见（城市）
    const displayedCities = computed(() => {
      const set = new Set(filteredCities.value)
      esCities.value.forEach((c) => set.add(c))
      ;(filters.city || []).forEach((c) => set.add(c))
      return Array.from(set)
    })

    // 添加部门翻译
    const departmentTranslations = {
      'Administrative': {zh: '行政', en: 'Administrative'},
      'Community And Social Services': {zh: '社区与社会服务', en: 'Community And Social Services'},
      'Education': {zh: '教育', en: 'Education'},
      'Engineering': {zh: '工程', en: 'Engineering'},
      'Executive': {zh: '高管/行政管理', en: 'Executive'},
      'Finance': {zh: '金融', en: 'Finance'},
      'Government': {zh: '政府', en: 'Government'},
      'Health Services': {zh: '医疗服务/医疗卫生', en: 'Health Services'},
      'Human Resources': {zh: '人力资源', en: 'Human Resources'},
      'Information Technology': {zh: '信息技术', en: 'Information Technology'},
      'Legal': {zh: '法律', en: 'Legal'},
      'Marketing': {zh: '市场营销', en: 'Marketing'},
      'Media And Communications': {zh: '媒体与传播', en: 'Media And Communications'},
      'Military And Protective Services': {zh: '军事与防护服务', en: 'Military And Protective Services'},
      'Operations': {zh: '运营', en: 'Operations'},
      'Product Management': {zh: '产品管理', en: 'Product Management'},
      'Real Estate': {zh: '房地产', en: 'Real Estate'},
      'Sales': {zh: '销售', en: 'Sales'}
    };

    // 为每个部门添加翻译
    const addDepartmentTranslations = () => {
      Object.keys(departmentTranslations).forEach(department => {
        const translations = departmentTranslations[department];
        addTranslation(`department.${department}`, {
          zh: translations.zh,
          en: translations.en
        });
      });
    };

    // 筛选后的部门列表
    const filteredDepartments = computed(() => {
      // 使用硬编码的部门列表
      const predefinedDepartments = Object.keys(departmentTranslations);

      // 根据搜索关键词筛选（支持中英文搜索）
      if (!departmentSearch.value) return predefinedDepartments;

      const currentLang = getCurrentLanguage();
      return predefinedDepartments.filter(department => {
        // 获取当前语言下的部门名称
        const translatedName = currentLang === 'zh' ?
            departmentTranslations[department].zh :
            departmentTranslations[department].en;

        // 同时搜索英文原名和翻译后的名称
        return department.toLowerCase().includes(departmentSearch.value.toLowerCase()) ||
            translatedName.toLowerCase().includes(departmentSearch.value.toLowerCase());
      });
    });

    // 合并显示：确保已选项始终可见（部门）
    // const displayedDepartments = computed(() => {
    //   const set = new Set(filteredDepartments.value)
    //   esDepartments.value.forEach((d) => set.add(d))
    //   ;(filters.department || []).forEach((d) => set.add(d))
    //   return Array.from(set)
    // })

    // 添加职业翻译
    const occupationTranslations = {
      'Account Manager': {zh: '客户经理', en: 'Account Manager'},
      'Business Development Director': {zh: '业务发展总监', en: 'Business Development Director'},
      'Marketing Manager': {zh: '市场营销经理', en: 'Marketing Manager'},
      'Sales Manager': {zh: '销售经理', en: 'Sales Manager'},
      'Human Resources Director': {zh: '人力资源总监', en: 'Human Resources Director'},
      'HR Manager': {zh: '人力资源经理', en: 'HR Manager'},
      'Project Manager': {zh: '项目经理', en: 'Project Manager'},
      'Software Developer': {zh: '软件开发工程师', en: 'Software Developer'},
      'Web Developer': {zh: 'Web开发工程师', en: 'Web Developer'},
      'Data Analyst': {zh: '数据分析师', en: 'Data Analyst'},
      'Systems Engineer': {zh: '系统工程师', en: 'Systems Engineer'},
      'Information Technology Manager': {zh: '信息技术经理', en: 'Information Technology Manager'},
      'Financial Analyst': {zh: '财务分析师', en: 'Financial Analyst'},
      'Accountant': {zh: '会计师', en: 'Accountant'},
      'Operations Manager': {zh: '运营经理', en: 'Operations Manager'},
      'Mechanical Engineer': {zh: '机械工程师', en: 'Mechanical Engineer'},
      'Electrical Engineer': {zh: '电气工程师', en: 'Electrical Engineer'},
      'Design Engineer': {zh: '设计工程师', en: 'Design Engineer'},
      'Registered Nurse': {zh: '注册护士', en: 'Registered Nurse'},
      'Occupational Therapist': {zh: '职业治疗师', en: 'Occupational Therapist'},
      'Physical Therapist': {zh: '物理治疗师', en: 'Physical Therapist'},
      'Lawyer': {zh: '律师', en: 'Lawyer'},
      'Executive Assistant': {zh: '行政助理', en: 'Executive Assistant'},
      'Office Manager': {zh: '办公室经理', en: 'Office Manager'},
      'Teacher': {zh: '教师', en: 'Teacher'},
      'Real Estate Agent': {zh: '房地产经纪人', en: 'Real Estate Agent'},
      'Chef': {zh: '厨师', en: 'Chef'},
      'Executive Chef': {zh: '行政总厨', en: 'Executive Chef'},
      'Construction Manager': {zh: '建筑经理', en: 'Construction Manager'},
      'Supply Chain Specialist': {zh: '供应链专员', en: 'Supply Chain Specialist'},
      'Logistics Coordinator': {zh: '物流协调员', en: 'Logistics Coordinator'},
      'Customer Service Manager': {zh: '客户服务经理', en: 'Customer Service Manager'},
      'Graphic Designer': {zh: '平面设计师', en: 'Graphic Designer'},
      'CAD Technician': {zh: 'CAD技术员', en: 'CAD Technician'},
      'Mechanic': {zh: '机械师', en: 'Mechanic'},
      'Technician': {zh: '技术员', en: 'Technician'},
      'Police Officer': {zh: '警察', en: 'Police Officer'},
      'Recruiter': {zh: '招聘人员', en: 'Recruiter'},
      'Talent Acquisition': {zh: '人才招聘', en: 'Talent Acquisition'}
    };

    // 为每个职业添加翻译
    const addOccupationTranslations = () => {
      Object.keys(occupationTranslations).forEach(occupation => {
        const translations = occupationTranslations[occupation];
        addTranslation(`occupation.${occupation}`, {
          zh: translations.zh,
          en: translations.en
        });
      });
    };

    // 筛选后的职业列表
    const filteredOccupations = computed(() => {
      // 使用硬编码的职业列表
      const predefinedOccupations = Object.keys(occupationTranslations);

      // 根据搜索关键词筛选（支持中英文搜索）
      if (!occupationSearch.value) return predefinedOccupations;

      const currentLang = getCurrentLanguage();
      return predefinedOccupations.filter(occupation => {
        // 获取当前语言下的职业名称
        const translatedName = currentLang === 'zh' ?
            occupationTranslations[occupation].zh :
            occupationTranslations[occupation].en;

        // 同时搜索英文原名和翻译后的名称
        return occupation.toLowerCase().includes(occupationSearch.value.toLowerCase()) ||
            translatedName.toLowerCase().includes(occupationSearch.value.toLowerCase());
      });
    });

    // 合并显示：确保已选项始终可见（职业）
    // const displayedOccupations = computed(() => {
    //   const set = new Set(filteredOccupations.value)
    //   esOccupations.value.forEach((o) => set.add(o))
    //   ;(filters.occupation || []).forEach((o) => set.add(o))
    //   return Array.from(set)
    // })

    // 处理城市搜索
    const handleCitySearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esCities.value = []
        return
      }

      try {
        esSearchLoading.value.city = true
        const response = await searchCitiesFromES(val)
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的城市
          const staticCityList = Object.keys(cityTranslations)
          esCities.value = response.data.filter(city => !staticCityList.includes(city))
        } else {
          esCities.value = []
        }
      } catch (error) {
        esCities.value = []
      } finally {
        esSearchLoading.value.city = false
      }
    }, 500)

    // 处理行业搜索
    const handleIndustrySearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esIndustries.value = []
        return
      }

      try {
        esSearchLoading.value.industry = true
        const response = await searchIndustriesFromES(val)
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的行业
          const staticIndustryList = Object.keys(industryTranslations)
          esIndustries.value = response.data.filter(industry => !staticIndustryList.includes(industry))
        } else {
          esIndustries.value = []
        }
      } catch (error) {
        esIndustries.value = []
      } finally {
        esSearchLoading.value.industry = false
      }
    }, 500)

    // 处理部门搜索（ES）
    const handleDepartmentSearch = debounce(async (val) => {
      if (!val || val.length < 1) {
        esDepartments.value = []
        return
      }

      esSearchLoading.value.department = true
      try {
        const response = await searchDepartmentsFromES(val)
        if (response && Array.isArray(response.data)) {
          const staticDepartmentList = Object.keys(departmentTranslations)
          esDepartments.value = response.data.filter(dep => !staticDepartmentList.includes(dep))
        } else {
          esDepartments.value = []
        }
      } catch (error) {
        esDepartments.value = []
      } finally {
        esSearchLoading.value.department = false
      }
    }, 500)

    // 处理职业搜索（ES）
    const handleOccupationSearch = debounce(async (val) => {
      if (!val || val.length < 1) {
        esOccupations.value = []
        return
      }

      esSearchLoading.value.occupation = true
      try {
        const response = await searchOccupationsFromES(val)
        if (response && Array.isArray(response.data)) {
          const staticOccupationList = Object.keys(occupationTranslations)
          esOccupations.value = response.data.filter(occ => !staticOccupationList.includes(occ))
        } else {
          esOccupations.value = []
        }
      } catch (error) {
        esOccupations.value = []
      } finally {
        esSearchLoading.value.occupation = false
      }
    }, 500)

    // 防抖函数
    function debounce(fn, delay) {
      let timer = null
      return function (...args) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    }

    return {
      loading,
      enterprises,
      currentPage,
      pageSize,
      totalEnterprise,
      formattedTotalEnterprise,
      hasSearched,
      queryParams,
      expanded,
      checkAll,
      isIndeterminate,
      filters,
      countrySearch,
      citySearch,
      industrySearch,
      departmentSearch,
      occupationSearch,
      filteredCountries,
      filteredCities,
      filteredIndustries,
      filteredDepartments,
      filteredOccupations,
      displayedCities,
      displayedIndustries,
      displayedDepartments,
      displayedOccupations,
      filteredEnterprises,
      paginatedEnterprises,
      // 分页限制相关
      realTotalEnterprise,
      maxSafePage,
      paginationTotal,
      isPaginationLimited,
      paginationLimitMessage,
      validatePageSafety,
      MAX_DATA_LIMIT, // 添加数据限制常量的导出
      getCountryFlag,
      handleFlagError,
      fetchEnterprises,
      toggleFilter,
      handleCheckAllChange,
      handleFilterChange,
      resetCompanySearch,
      resetAllFilters,
      handleLogin,
      toggleEnterpriseDetails,
      handleSizeChange,
      handleCurrentChange,
      handleEmployeeChange,
      handleReveneuChange,
      handleContactChange,
      getAvatarColor,
      getAvatarStyle,
      addHttpPrefix,
      // 导出相关
      exportLoading,
      exportData,
      exportDialogVisible,
      totalMatchCount,
      exportCount,
      userBalance,
      isExportCountExceeded,
      isBalanceInsufficient,
      isExportLimitExceeded,
      doExport,
      // 字段选择相关
      selectedFields,
      allFields,
      currentLanguage,
      initSelectedFields,
      updateSelectedFields,
      selectAllFields,
      selectNoFields,
      isAllFieldsSelected,
      isNoFieldsSelected,
      // 添加详情查看相关
      detailViewLoading,
      viewDetailInfo,
      // 添加t函数（返回本地包装的 t，支持默认值回退）
      t,
      // 添加Download图标供模板使用
      Download: iconDownload,
      // ES查询相关
      esCities,
      esIndustries,
      esDepartments,
      esOccupations,
      esSearchLoading,
      handleCitySearch,
      handleIndustrySearch,
      handleDepartmentSearch,
      handleOccupationSearch,
      // 过滤项显示标签
      getFilterLabel
    }
  }
}
</script>

<style scoped>
.global-enterprise-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.search-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.search-box-container {
  display: flex;
  justify-content: space-between;
  gap: 30px;
  width: 100%;
  max-width: 1300px;
}

.search-input {
  flex: 1;
  min-width: 120px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .search-box-container {
    flex-direction: column;
    max-width: 400px;
  }

  .search-input {
    width: 100%;
  }
}

:deep(.el-input__inner) {
  font-size: 16px;
  height: 45px;
  text-align: center;
}

/* 导出数据模块 */
.export-module {
  background: #fff;
  border-radius: 6px;
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.export-module-btn {
  height: 40px;
  background-color: #409eff;
  color: white;
}

/* 主内容区布局 */
.enterprise-main {
  display: flex;
  gap: 20px; /* 筛选器与内容区之间的间隔 */
  flex: 1;
}

/* 筛选侧边栏样式 */
.filter-sidebar-container {
  width: 280px;
  flex-shrink: 0; /* 防止侧边栏宽度被压缩 */
  position: relative; /* 为固定定位做准备 */
}

.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  position: sticky; /* 使筛选器在滚动时保持可见 */
  top: 20px; /* 距离顶部的距离 */
  max-height: calc(100vh - 100px); /* 最大高度，确保在小屏幕上可以滚动 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
}

/* 重置筛选器按钮 */
.reset-filter-container {
  margin-bottom: 15px;
  text-align: center;
}

.reset-filter-btn {
  width: 100%;
}

/* 筛选组样式 */
.filter-group {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden; /* 防止内容溢出 */
  padding-bottom: 0;
  border-bottom: none;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-group.expanded {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 0;
}

.filter-content {
  padding: 15px;
  max-height: 250px; /* 限制最大高度 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
  margin-top: 0;
}

/* 筛选器内搜索框 */
.filter-search {
  margin-bottom: 10px;
  position: relative;
}

.filter-search.is-loading .el-input__inner {
  padding-right: 95px; /* 为加载状态文本留出空间 */
}

.filter-search-loading {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #409eff;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 0 5px;
  border-radius: 3px;
  z-index: 2;
}

.filter-search-loading i {
  margin-right: 5px;
  font-size: 14px;
  animation: rotating 1s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 右侧数据内容样式 */
.data-content {
  flex: 1;
}

.search-module {
  background: #fff;
  border-radius: 6px;
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-input-container {
  display: flex;
  align-items: center;
  flex: 1;
}

.search-input-module {
  flex: 1;
  max-width: 500px;
}

.search-btn {
  margin-left: 15px;
  height: 40px;
}

.total-info {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  margin-left: 15px;
}

/* 企业卡片列表样式 */
.enterprise-card-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-height: 100px;
  width: 100%;
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.enterprise-card {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  border: 1px solid #ebeef5;
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  word-wrap: break-word;
  word-break: break-word;
}

.enterprise-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.company-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0; /* 允许flex子元素收缩 */
  overflow: hidden;
}

.company-avatar {
  width: 45px;
  height: 45px;
  margin-right: 12px;
}

.cartoon-avatar {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  word-break: break-all;
  line-height: 1.4;
}

.detail-button {
  flex-shrink: 0;
  margin-top: 5px;
}

.detail-btn {
  font-size: 15px;
  padding: 8px 16px;
  height: auto;
  font-weight: normal;
  border-radius: 4px;
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #b3d8ff;
}

.card-basic-info {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.basic-info-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: baseline;
  min-width: 45%;
  max-width: 100%;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-word;
  box-sizing: border-box;
}

.info-label {
  font-weight: 500;
  color: #666;
  margin-right: 39px;
  min-width: 80px;
  width: 80px;
  text-align: right;
  display: inline-block;
  white-space: nowrap;
}

.info-value {
  color: #333;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-word;
  line-height: 1.4;
  max-width: 100%;
}

/* 单行文本信息值（如国家、行业等） */
.info-value.single-line {
  white-space: nowrap;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
}

/* 多行文本信息值（如描述、地址等） - 允许更多内容 */
.info-value.multi-line {
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  line-clamp: 4; /* 标准属性 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 6em; /* 约4行文本的高度 */
  line-height: 1.5;
}

/* 完全无限制的文本显示（用于特殊需要） */
.info-value.full-text {
  white-space: normal;
  max-height: none;
  overflow: visible;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-word;
}

/* URL链接特殊处理 */
.info-value.url-link {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  max-width: 200px;
}

.info-value.url-link a {
  color: #409eff;
  text-decoration: none;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100%;
}

.info-value.url-link a:hover {
  text-decoration: underline;
}

.country-flag {
  width: 20px;
  height: 15px;
  margin-right: 5px;
  border-radius: 2px;
  vertical-align: middle;
  object-fit: cover;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
  padding-left: 15px;
}

.info-table-wrapper {
  padding: 0 8px;
  overflow-x: hidden;
  overflow-y: visible;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 10px; /* 增加底部间距 */
}

.info-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  word-wrap: break-word;
  word-break: break-word;
}

/* 地址行的特殊布局 - 为地址列分配更多空间 */
.info-table tr.address-row .label-cell {
  width: 70px; /* 稍微减少标签列宽度 */
}

.info-table tr.address-row .value-cell.address-cell {
  width: calc(60% - 75px); /* 为地址列分配更多空间 */
}

.info-table tr.address-row .value-cell:not(.address-cell) {
  width: calc(40% - 75px); /* 其他列相应减少 */
}

.info-table tbody tr {
  border-bottom: none;
  vertical-align: top; /* 确保所有单元格顶部对齐 */
}

.info-table tbody tr:last-child {
  border-bottom: none;
}

/* 为包含长文本的行添加额外的底部间距 */
.info-table tbody tr.address-row {
  border-bottom: none;
  margin-bottom: 5px;
}

/* 新增：部门行在下方增加分隔线 */
.info-table tbody tr.department-row {
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 5px;
}

.info-table tbody tr.address-row td {
  padding-bottom: 15px; /* 增加底部间距 */
}

/* 新增：部门行的底部间距 */
.info-table tbody tr.department-row td {
  padding-bottom: 15px;
}

.label-cell {
  padding: 8px 5px;
  font-weight: 500;
  color: #666;
  text-align: right;
  vertical-align: top;
  width: 80px;
  white-space: nowrap;
}

.value-cell {
  width: calc(50% - 85px);
  padding: 8px 5px;
  color: #333;
  vertical-align: top;
  word-wrap: break-word;
  word-break: break-word;
  max-width: 0; /* 配合table-layout: fixed使用 */
  overflow: hidden;
  line-height: 1.4;
}

/* 单行文本的表格单元格 */
.value-cell.single-line {
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 多行文本的表格单元格 - 保留一定限制以保持整洁 */
.value-cell.multi-line {
  white-space: normal;
  max-height: 6em; /* 约4行文本，适度增加 */
  display: -webkit-box;
  -webkit-line-clamp: 4;
  line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  vertical-align: top;
}

/* 地址专用的表格单元格 - 完整显示所有内容，与其他字段样式一致 */
.value-cell.address-cell {
  white-space: normal;
  /* 移除高度和行数限制，允许完整显示 */
  max-height: none;
  overflow: visible;
  line-height: 1.4; /* 与基础value-cell一致 */
  word-wrap: break-word;
  word-break: break-word;
  padding: 8px 5px; /* 与基础value-cell一致的内边距 */
  color: #333; /* 与基础value-cell一致的文字颜色 */
  vertical-align: top; /* 确保顶部对齐 */
  /* 移除背景色、圆角、特殊字体大小，完全继承基础样式 */
}

/* 地址单元格悬停效果 - 移除特殊悬停效果，与其他字段保持一致 */

/* 通用长文本单元格样式 - 用于其他可能的长文本字段 */
.value-cell.long-text {
  white-space: normal;
  max-height: none;
  overflow: visible;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-word;
  padding: 8px 5px 10px 5px;
  vertical-align: top;
  min-height: 2em;
}

/* 公司名称在表格中的特殊处理 */
.value-cell.company-name {
  white-space: normal;
  max-height: none;
  overflow: visible;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-word;
  font-weight: 500;
  color: #333;
  vertical-align: top;
}

/* URL链接的表格单元格 */
.value-cell.url-cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 200px;
}

.value-cell a {
  color: #409eff;
  text-decoration: none;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100%;
}

.value-cell a:hover {
  text-decoration: underline;
}

/* 分页限制提示样式 */
.pagination-limit-notice {
  margin-top: 15px;
  margin-bottom: 15px;
}

.limit-alert {
  border-radius: 8px;
  border: 1px solid #e1f3ff;
  background-color: #f4f9ff;
}

.limit-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.limit-tip {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.limit-technical {
  font-size: 11px;
  color: #c0c4cc;
  font-style: italic;
  margin-top: 3px;
  padding-top: 3px;
  border-top: 1px solid #e1f3ff;
}

/* 分页控件样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式优化 - 移动端分页限制提示 */
@media (max-width: 768px) {
  .pagination-limit-notice {
    margin: 10px 0;
  }

  .limit-content {
    font-size: 13px;
  }

  .limit-tip {
    font-size: 11px;
  }

  /* 移动端企业卡片优化 */
  .enterprise-card {
    margin-bottom: 10px;
  }

  .card-header {
    padding: 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .company-info {
    width: 100%;
  }

  .company-name {
    font-size: 14px;
    white-space: normal;
    line-height: 1.3;
    max-height: 2.6em; /* 约2行文本 */
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .detail-button {
    width: 100%;
    margin-top: 0;
  }

  .detail-btn {
    width: 100%;
    font-size: 14px;
    padding: 6px 12px;
  }

  .card-basic-info {
    padding: 8px 12px;
  }

  .info-row {
    flex-direction: column;
    gap: 8px;
  }

  .info-item {
    min-width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .info-label {
    min-width: auto;
    width: auto;
    text-align: left;
    font-size: 12px;
    color: #999;
  }

  .info-value {
    font-size: 14px;
    width: 100%;
  }

  .info-value.single-line {
    white-space: normal;
    word-break: break-word;
  }

  .info-table-wrapper {
    padding: 0 4px;
  }

  .info-table {
    font-size: 13px;
  }

  .label-cell {
    width: 70px;
    font-size: 12px;
    padding: 6px 3px;
  }

  .value-cell {
    width: calc(100% - 75px);
    font-size: 13px;
    padding: 6px 3px;
  }

  .value-cell.single-line {
    white-space: normal;
    word-break: break-word;
  }

  /* 移动端地址单元格优化 - 完整显示，与其他字段样式一致 */
  .value-cell.address-cell {
    max-height: none; /* 移除高度限制 */
    overflow: visible; /* 允许完整显示 */
    /* 继承移动端.value-cell的所有样式：padding: 6px 3px, font-size: 13px, color: #333 */
  }

  /* 移动端地址行布局优化 */
  .info-table tr.address-row .label-cell {
    width: 60px;
    padding-top: 10px; /* 增加顶部对齐间距 */
  }

  .info-table tr.address-row .value-cell.address-cell {
    width: calc(100% - 65px);
  }

  /* 移动端表格行间距优化 */
  .info-table tbody tr.address-row td {
    padding-bottom: 20px; /* 移动端增加更多底部间距 */
  }

  /* 新增：移动端为部门行也增加更多底部间距 */
  .info-table tbody tr.department-row td {
    padding-bottom: 20px;
  }

  /* 移动端长文本单元格通用样式 */
  .value-cell.long-text {
    font-size: 12px;
    line-height: 1.6;
    padding: 6px 3px 8px 3px;
  }
}

/* 平板端优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .enterprise-card {
    margin-bottom: 12px;
  }

  .company-name {
    font-size: 15px;
  }

  .info-item {
    min-width: 100%;
  }

  .info-row {
    flex-direction: column;
    gap: 10px;
  }

  .value-cell {
    width: calc(100% - 85px);
  }

  /* 平板端地址单元格优化 - 完整显示，与其他字段样式一致 */
  .value-cell.address-cell {
    max-height: none; /* 移除高度限制 */
    overflow: visible; /* 允许完整显示 */
    /* 继承基础.value-cell的所有样式，无需重复设置 */
  }

  /* 平板端地址行布局 */
  .info-table tr.address-row .value-cell.address-cell {
    width: calc(65% - 85px);
  }

  .info-table tr.address-row .value-cell:not(.address-cell) {
    width: calc(35% - 85px);
  }
}

/* 无数据提示样式 */
.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

.login-btn {
  margin-top: 15px;
  width: 200px;
}

/* 骨架屏样式 */
.skeleton-loading {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.skeleton-card {
  background: #fff;
  border-radius: 6px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.skeleton-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.skeleton-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  margin-right: 10px;
}

.skeleton-title {
  height: 20px;
  width: 150px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 4px;
}

.skeleton-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.skeleton-line {
  height: 16px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 4px;
}

.skeleton-line:nth-child(1) {
  width: 100%;
}

.skeleton-line:nth-child(2) {
  width: 80%;
}

.skeleton-line:nth-child(3) {
  width: 60%;
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.matched-count {
  font-size: 16px;
  color: #606266;
  margin-right: 20px;
  font-weight: 500;
}

.matched-count-number {
  color: #409eff;
  font-weight: bold;
  margin: 0 2px;
}

.data-limit-notice {
  color: #E6A23C;
  font-size: 14px;
  margin-left: 5px;
}

/* 添加遮蔽信息的样式 */
.masked-info {
  color: #409eff;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  position: relative;
  padding-right: 20px;
}

.masked-info:hover {
  text-decoration: underline;
}

.info-lock-icon {
  font-size: 14px;
  margin-left: 5px;
  color: #909399;
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 字段选择区域样式 */
.field-selection {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.field-selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.field-selection-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.field-selection-actions {
  display: flex;
  gap: 8px;
}

.field-selection-content {
  margin-top: 10px;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 10px;
}

.field-item {
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.field-item:hover {
  background-color: #f0f9ff;
}

.field-item .el-checkbox {
  width: 100%;
  cursor: pointer;
}

.field-item .el-checkbox__label {
  width: 100%;
  padding-left: 8px;
  cursor: pointer;
}

.field-unselected {
  color: #909399 !important;
  font-weight: normal;
}

.field-warning {
  color: #f56c6c;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
}

/* ES查询结果分隔线 */
.es-result-divider {
  padding: 8px 0;
  margin: 8px 0;
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
  border-top: 1px dashed #e0e0e0;
  border-bottom: 1px dashed #e0e0e0;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 3px;
}
</style>